<?php

/**
 * Classe PromoCritere
 * @author Jeremy
 * @version 0.5
 * @todo Finir la classe
 */
class PromoCritere
{

    /**
     * @var int
     */
    private $Id;
    /**
     * @var int
     */
    private $IdPromo;
    /**
     * @var int
     */
     private $NbEtudiantMax;
     /**
      * @var int
      */
     private $NbEtudiant;


     static public function getListByIdEnseignant($id = 0)
     {
         if (empty($id))
        {
            return array();
        }
        else
        {
            $sql = SQL::getInstance()->getConnection();
            //On retourne l'entree demandee
            $query = '
                        SELECT PromoCritere.*
                        FROM PromoCritere
                        INNER JOIN CritereEnseignantRS ON CritereEnseignantRS.IdCritere = PromoCritere.IdPromoCritere
                        WHERE CritereEnseignantRS.IdTypeCritere = 1 AND CritereEnseignantRS.IdEnseignant = :idE
                    ';
            $c = $sql->prepare($query);
            $c->bindParam(':idE', $id, PDO::PARAM_INT);
            //Execution de la requête retourne false si echec
            if ($c->execute())
            {
                $result = $c->fetchAll(PDO::FETCH_OBJ);
                if (!empty($result))
                {
                    $lst = array();
                    foreach($result as $key => $object)
                    {
                        $lst[$object->IdPromo]['NbEtudiantMax'] = $object->NbEtudiantMax;
                        $lst[$object->IdPromo]['NbEtudiant'] = $object->NbEtudiant;
                        $lst[$object->IdPromo]['IdPromoCritere'] = $object->IdPromoCritere;
                    }
                    return $lst;
                }
                else
                {
                    return array();
                }
            }
            else
            {
                return array();
            }
        }
     }

     /**
      * Met à jour le nombre d'étudiant
      * 
      */
     static public function updateNbEtudiant($stage, $idEnseignant)
     {
         $error = null;
         $idEtudiant = $stage->getIdEtudiant();
         $Etudiant = new Etudiant($idEtudiant);
         $sql = SQL::getInstance()->getConnection();
         if($stage->getIdTuteurEnseignant() != $idEnseignant){
             $idPromo = $Etudiant->getIdPromo();
             //On retire un étudiant de l'ancien prof
             $listCritere = CritereEnseignant::getListIdCritereByIdEnseignant($stage->getIdTuteurEnseignant());
             if(count($listCritere) > 0){
                foreach($listCritere as $critere){
                    $query = "UPDATE PromoCritere SET
                                  NbEtudiant = NbEtudiant - 1
                                  WHERE IdPromoCritere = :id
                                  AND NbEtudiant > 0
                                  AND IdPromo = :idp";
                    $c = $sql->prepare($query);
                    $c->bindParam(":id", $critere->IdCritere, PDO::PARAM_INT);
                    $c->bindParam(":idp", $idPromo, PDO::PARAM_INT);
                    $c->execute();
                }
             }
             //On ajoute un étudiant au nouveau prof
             $listCritere = CritereEnseignant::getListIdCritereByIdEnseignant($idEnseignant);
             if(count($listCritere) > 0){
                $sql = SQL::getInstance()->getConnection();
                foreach($listCritere as $critere){
                    $query = "SELECT * FROM PromoCritere
                                  WHERE IdPromoCritere = :id
                                  AND IdPromo = :idp";
                    $c = $sql->prepare($query);
                    $c->bindParam(":id", $critere->IdCritere, PDO::PARAM_INT);
                    $c->bindParam(":idp", $idPromo, PDO::PARAM_INT);
                    if($c->execute()){
                        $result = $c->fetch(PDO::FETCH_OBJ);
                        if($result->NbEtudiant < $result->NbEtudiantMax){
                            $query = "UPDATE PromoCritere SET
                                      NbEtudiant = NbEtudiant - 1
                                      WHERE IdPromoCritere = :id";
                            $c = $sql->prepare($query);
                            $c->bindParam(":id", $result->IdPromoCritere, PDO::PARAM_INT);
                            $c->execute();
                        }//else
                           // $error = "Cet enseignant a d&eacute;j&agrave; atteint le nombre maximal d'&eacute;tudiant qu'il d&eacute;sirait.";
                    }
                }
             }
         }
         return $error;
     }


     // ---------------------------- CRUD et accesseurs ----------------------------------

    /**
     *
     * @param int $id
     */
    public function __construct($id = 0)
    {
        if (isset($id) && !empty($id))
        {
           $sql = SQL::getInstance()->getConnection();

            $query = "	SELECT PromoCritere.*
			FROM PromoCritere
			WHERE PromoCritere.IdPromoCritere = :id
		";
            $c = $sql->prepare($query);
            $c->bindParam(":id", $id, PDO::PARAM_INT);

            if ($c->execute())
            {
                $result = $c->fetch(PDO::FETCH_OBJ);

                $this->Id               = $result->IdPromoCritere;
                $this->IdPromo          = $result->IdPromo;
                $this->NbEtudiantMax    = $result->NbEtudiantMax;
                $this->NbEtudiant       = $result->NbEtudiant;

                $this->errormsg = "recuperee";
                $this->requeteOk = true;
            }
            else
            {
                $this->Id               = 0;
                $this->IdPromo          = 0;
                $this->NbEtudiantMax    = 0;
                $this->NbEtudiant       = 0;

                $this->errormsg = "SQL Failed";
                $this->requeteOk = false;
            }
            $c->closeCursor();
        }
        else
        {
            $this->Id               = 0;
            $this->IdPromo          = 0;
            $this->NbEtudiantMax    = 0;
            $this->NbEtudiant       = 0;

            $this->errormsg = "vierge";
        }
    }

    /**
     * Insert une promo dans la base
     */
    public function insert()
    {
        $sql = SQL::getInstance()->getConnection();
        $query =
                'INSERT INTO PromoCritere
		(
			 IdPromo,
			 NbEtudiantMax,
                         NbEtudiant
		)
		VALUES
		(
			:idP,
			:nbMax,
                        :nbE
		)';
        $sql->beginTransaction();
        try
        {
            $c = $sql->prepare($query);

            $c->bindParam(':idP', $this->IdPromo, PDO::PARAM_INT);
            $c->bindParam(':nbMax', $this->NbEtudiantMax, PDO::PARAM_INT);
            $c->bindParam(':nbE', $this->NbEtudiant, PDO::PARAM_INT);

            if ($c->execute())
            {
                $this->Id = $sql->lastInsertId();
                $sql->commit();
                $c->closeCursor();
                $this->requeteOk = true;
                $this->errormsg = "Insertion reussie!";
            }
            else
            {
                $this->requeteOk = false;
                $this->errormsg = $c->errorInfo();
                $sql->rollback();
                $c->closeCursor();
                $this->Id = 0;
            }
        }
        catch (PDOException $Exception)
        {
            $this->requeteOk = false;
            $this->errormsg = $c->errorInfo();
            $sql->rollback();
            $c->closeCursor();
            $this->Id = 0;
        }
    }

    /**
     * Met à jour le nom de la promo dans la base
     */
    public function update()
    {
        $sql = SQL::getInstance()->getConnection();
        $query =
                'UPDATE PromoCritere SET
			 IdPromo                = :idP,
			 NbEtudiantMax          = :nbMax,
                         NbEtudiant             = :nbE
		WHERE
			IdPromoCritere          = :id
		';
        $sql->beginTransaction();
        try
        {
            $c = $sql->prepare($query);

            $c->bindParam(':id', $this->Id, PDO::PARAM_INT);
            $c->bindParam(':idP', $this->IdPromo, PDO::PARAM_INT);
            $c->bindParam(':nbMax', $this->NbEtudiantMax, PDO::PARAM_INT);
            $c->bindParam(':nbE', $this->NbEtudiant, PDO::PARAM_INT);

            if ($c->execute())
            {
                $sql->commit();
                $c->closeCursor();
                $this->requeteOk = true;
                $this->errormsg = "Modification reussie!";
            }
            else
            {
                $this->requeteOk = false;
                $this->errormsg = $c->errorInfo();
                $sql->rollback();
                $c->closeCursor();
            }
        }
        catch (PDOException $Exception)
        {
            $this->requeteOk = false;
            $this->errormsg = $c->errorInfo();
            $sql->rollback();
            $c->closeCursor();
        }
    }

    /**
     * supprime une promo
     */
    public function delete()
    {
        $sql = SQL::getInstance()->getConnection();

        $query = 'DELETE FROM PromoCritere WHERE IdPromoCritere = :id';
        $c = $sql->prepare($query);
        $c->bindParam(':id', $this->Id, PDO::PARAM_INT);
        $c->execute();
    }

    /**
     *
     * @return int
     */
    public function getId()
    {
        return $this->Id;
    }

    /**
     *
     * @return int
     */
    public function getIdPromo()
    {
        return $this->IdPromo;
    }

    public function setIdPromo($value)
    {
        //echo "setIdPromo($value)";
        //Verif Type + verif Nulle, si bon mis a jour, sinon message erreur
        $errTab = array("boolOk" => true, "errmsg" => "");

        if (isset($value) && $value > 0)
        {
            $this->IdPromo = $value;
        }
        else
        {
            if (!isset($value))
            {
                $errTab["boolOk"] = false;
                $errTab["errmsg"] = "L'Id ne peut etre null !";
            }
            if (isset($value) && $value <= 0)
            {
                $errTab["boolOk"] = false;
                $errTab["errmsg"] = "L'Id ne peut etre <= 0 !";
            }
            else
            {
                $errTab["boolOk"] = false;
                $errTab["errmsg"] = "Cet Id n'est pas valide !";
            }

            $this->IdPromo = 0;
        }
        return $errTab;
    }



    /**
     *
     * @return int
     */
    public function getNbEtudiantMax()
    {
        return $this->NbEtudiantMax;
    }

    public function setNbEtudiantMax($value)
    {
        //Verif Type + verif Nulle, si bon mis a jour, sinon message erreur
        $errTab = array("boolOk" => true, "errmsg" => "");

        if (isset($value) && $value > 0)
        {
            $this->NbEtudiantMax = $value;
        }
        else
        {
            if (!isset($value))
            {
                $errTab["boolOk"] = false;
                $errTab["errmsg"] = "L'Id ne peut etre null !";
            }
            if (isset($value) && $value <= 0)
            {
                $errTab["boolOk"] = false;
                $errTab["errmsg"] = "L'Id ne peut etre <= 0 !";
            }
            else
            {
                $errTab["boolOk"] = false;
                $errTab["errmsg"] = "Cet Id n'est pas valide !";
            }

            $this->NbEtudiantMax = 0;
        }
        return $errTab;
    }

    /**
     *
     * @return int
     */
    public function getNbEtudiant()
    {
        return $this->NbEtudiant;
    }

    public function setNbEtudiant($value)
    {
        //Verif Type + verif Nulle, si bon mis a jour, sinon message erreur
        $errTab = array("boolOk" => true, "errmsg" => "");

        if (isset($value) && $value > 0)
        {
            $this->NbEtudiant = $value;
        }
        else
        {
            if (!isset($value))
            {
                $errTab["boolOk"] = false;
                $errTab["errmsg"] = "L'Id ne peut etre null !";
            }
            if (isset($value) && $value <= 0)
            {
                $errTab["boolOk"] = false;
                $errTab["errmsg"] = "L'Id ne peut etre <= 0 !";
            }
            else
            {
                $errTab["boolOk"] = false;
                $errTab["errmsg"] = "Cet Id n'est pas valide !";
            }

            $this->NbEtudiant = 0;
        }
        return $errTab;
    }
}

?>